﻿package tools;

/**
 * 自定义链表[递归]
 * */
public class LinkDemo {

	public static void main(String[] args) {
		MyNode root = new MyNode("A");
		MyNode n1 = new MyNode("B");
		MyNode n2 = new MyNode("C");
		MyLink ml = new MyLink();
		ml.addNode(root);
		ml.addNode(n1);
		ml.addNode(n2);
		ml.printLink();
		System.out.println();
		System.out.println("A in ml?" + ml.containNode("A"));
		System.out.println("B in ml?" + ml.containNode("B"));
		ml.delNode("A");
		ml.delNode("B");
		ml.delNode("C");
		ml.printLink();
		
	}

}

class MyLink {
	MyNode root = null;

	public void addNode(MyNode node) {
		if (root == null) {
			root = node;
		} else {
			root.add(node);
		}
	}

	public boolean containNode(String data) {
		if (root == null) {
			return false;
		} else {
			return root.contain(data);
		}
	}

	public void delNode(String data) {
		if (root == null) {
			return;
		} else if(!this.containNode(data)){
			return;
		}else if(root.getData().equals(data)){
			root = root.getNext();
		}else{
			root.delete(root,data);
		}
	}

	public void printLink() {
		if(root==null){
			System.out.println("Link is empty");
		}else{
			root.printNode();
		}
	}

}

class MyNode {

	private String data;
	private MyNode next;

	public MyNode() {
		this.data = "NULL";
	}

	public MyNode(String data) {
		this.data = data;
	}

	public void add(MyNode node) {
		if (this.next == null) {
			this.next = node;
		} else {
			this.next.add(node);
		}
	}

	public boolean contain(String data) {
		if (this.data == data) {
			return true;
		} else if (this.getNext() != null) {
			return this.getNext().contain(data);
		} else {
			return false;
		}
	}

	public void delete(MyNode prenode,String data) {
		if(this.data.equals(data)){
			prenode.next=this.next;
		}else{
			if(this.next!=null){
				this.next.delete(this, data);
			}
		}
	}

	public void printNode() {
		System.out.print(this.getData()+"\t");
		if (this.next != null) {
			this.next.printNode();
		}

	}

	public void setNext(MyNode node) {
		this.next = node;
	}

	public String getData() {
		return this.data;
	}

	public MyNode getNext() {
		return next;
	}

	public void setData(String data) {
		this.data = data;
	}
}